// jwt鉴权策略

import { ExtractJwt, Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common'
import { jwtConstants } from '../constants'
import { UserService } from 'src/database/user/user.service'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    })
  }

  /**
  * 验证用户Token是否存在且正确
  * 验证成功：会在request中增加一个来源于数据库的user对象（req.user），即方法的返回值
  * 验证失败：自动抛出UnauthorizedException
  */
  async validate(payload: any) {
    
    const { sub: uid, username } = payload
    const user = await this.userService.findOne(uid);    
    console.log(user);
    
    return user;
  }
}